import React, { Component } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  Modal,
  TouchableOpacity,
  Dimensions,
  Animated, Image
} from 'react-native';

const { height: SCREEN_HEIGHT } = Dimensions.get('window');
import { getImgUrl, getCarRegisterDate, getMileFormat, getPriceFormat, getStoreStatus, getSaleStatus, getCheckStatus, formatTimestamp } from '../../utils/ComFunction';

import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'
import { ToastToUser } from '../../utils/CustomToast';
import { getMsgContentShow } from "../../utils/ComFunction";

class QuotationListModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: false,
      pageNo: 1,
      modalAnimation: new Animated.Value(0),
      isEnableLoadMore: true
    };
  }

  componentDidMount() {
    console.log('componentDidMount')
    if (this.props.visible) {
      this.animateIn();
    }
    this.getUserConversationList()
  }

  componentDidUpdate(prevProps) {
    if (this.props.visible && !prevProps.visible) {
      this.animateIn();
    } else if (!this.props.visible && prevProps.visible) {
      this.animateOut();
    }

    // console.log('componentDidUpdate', prevProps)
  }

  animateIn = () => {
    Animated.timing(this.state.modalAnimation, {
      toValue: 1,
      duration: 300,
      useNativeDriver: true,
    }).start();
  };

  animateOut = () => {
    Animated.timing(this.state.modalAnimation, {
      toValue: 0,
      duration: 300,
      useNativeDriver: true,
    }).start();
  };

  loadMoreData = () => {
    if (this.state.loading) return;
    if (!this.state.isEnableLoadMore) {
      return
    }
    this.setState({ loading: true });

    this.getUserConversationList()


  };

  renderItem = ({ item, index }) => (
    <View style={styles.quotationItem} key={index}>
      <TouchableOpacity style={styles.itemHeader}
        onPress={() => {
          // this.props.onClose()
          //这里延时一下，不然报价中心有返回按钮
          setTimeout(() => {
            let msgParams = {
              imGroupId: item.imGroupId + '',
              carId: item.consultingCarId + '',
              quotationRecordId: item.quotationRecord && item.quotationRecord.quotationRecordId ? item.quotationRecord.quotationRecordId : '',
            }
            this.props.navigation.navigate('MessageChat', msgParams)
          }, 250);
        }}>

        <Image style={styles.avatar} source={{ uri: getImgUrl(item.buyerMerchantLogo) }} />

        <View style={styles.userInfo}>

          <View style={styles.nameContainer}>

            <Text style={styles.userName}>{item.buyerUserName + '@' + item.buyerMerchantName}</Text>

            {(item.quotationRecord && item.quotationRecord.quotationRecordStatus == 1 && item.quotationRecord.historyRO.isReject == 0) || item.quotationRecord.quotationRecordStatus == 2
              || item.quotationRecord.quotationRecordStatus == 3 ?
              <Text style={styles.price}>收: {item.quotationRecord.quotationPrice / (100 * 10000)}万元</Text>
              : <View></View>
            }
          </View>

          <Text style={[styles.date, { marginTop: 3 }]} numberOfLines={1} ellipsizeMode='tail'>{getMsgContentShow(item.imConversationInfo.msgInfo)} </Text>

          <View style={{ flexDirection: 'row' }}>
            <Text style={styles.date}>{formatTimestamp(item.imConversationInfo.msgInfo.LatestMsgRecvTime)}</Text>
            <View style={{ flex: 1 }}></View>

            {item.quotationRecord && item.quotationRecord.quotationPrice ?
              <View style={styles.buttonContainer}>

                {item.quotationRecord.quotationRecordStatus == 1 && item.quotationRecord.historyRO.isReject == 0 ?
                  <TouchableOpacity style={styles.confirmButton}
                    onPress={() => {
                      this.props.navigation.navigate('StartOrderPage', {
                        carId: this.props.carId, quotationRecordId: item.quotationRecord.quotationRecordId, merchantId: item.buyerMerchantId,
                        buyerMerchantName: item.buyerMerchantName
                      })
                      this.props.onClose()
                    }}>
                    <Text style={styles.buttonText}>确认交易</Text>
                  </TouchableOpacity>
                  : null
                }

                {item.quotationRecord.quotationRecordStatus == 1 && item.quotationRecord.historyRO.isReject == 0 ?
                  <TouchableOpacity style={styles.confirmButton}
                    onPress={() => { this.quotationReject(item.quotationRecord.quotationRecordId) }}>
                    <Text style={styles.buttonText}>驳回报价</Text>
                  </TouchableOpacity>
                  : null
                }

                {item.quotationRecord.quotationRecordStatus == 2 || item.quotationRecord.quotationRecordStatus == 3 ?
                  <TouchableOpacity style={styles.confirmButton}
                    onPress={() => { this.cancelOrder(item.quotationRecord.quotationRecordId) }}>
                    <Text style={styles.buttonText}>取消报价</Text>
                  </TouchableOpacity>
                  :
                  null
                }

              </View>
              : <View></View>
            }
          </View>

        </View>

      </TouchableOpacity>

      {/**
           * 买家未报价：无价格、无按钮
              买家已报价：价格、确认交易、驳回报价
              卖家已驳回：无价格、无按钮
            卖家已发单：价格、取消报价
            卖家已确认：价格、取消报价
            买家已取消：无价格、无按钮
            卖家已取消：无价格、无按钮
           */}



    </View>
  );

  render() {
    const translateY = this.state.modalAnimation.interpolate({
      inputRange: [0, 1],
      outputRange: [SCREEN_HEIGHT, 0],
    });

    return (
      <View style={styles.modalContainer}>
        <TouchableOpacity
          style={styles.overlay}
          activeOpacity={1}
          onPress={this.props.onClose}
        />
        <Animated.View
          style={[
            styles.contentContainer,
            {height: SCREEN_HEIGHT * 0.66- (this.props.isRoot ? (50+Constant.bottomHeight):0)},
            { transform: [{ translateY }] }
          ]}
        >
          <View style={styles.header}>
            <Text style={styles.title}>{this.props.quotationProgressStatus == 4 ? '待确认列表' : '沟通中列表'}</Text>

          </View>
          <FlatList
            data={this.state.data}
            renderItem={this.renderItem}
            keyExtractor={(item, index) => index + ''}
            onEndReached={this.loadMoreData}
            onEndReachedThreshold={0.1}
            ListFooterComponent={
              this.state.loading ?
                <Text style={styles.loading}>加载中...</Text> :
                null
            }
          />
          {/* <View style={styles.line}></View>
          <TouchableOpacity
            style={[styles.cancelBtn, { marginBottom: this.props.isRoot ? 0:Constant.bottomHeight }]}
            onPress={this.props.onClose}>
            <Text style={styles.closeButton}>取消</Text>
          </TouchableOpacity> */}
        </Animated.View>
      </View>
    );
  }

  getMsgTypeDes(msgInfo) {
    if (msgInfo.contentType == 101) {//文本消息
      return msgInfo.senderName + '：' + JSON.parse(msgInfo.content).content
    } else if (msgInfo.contentType == 102) {//图片消息

      return msgInfo.senderName + '：' + '[图片]'
    } else if (msgInfo.contentType == 103) {//语音消息
      return msgInfo.senderName + '：' + '[语音]' + JSON.parse(msgInfo.content).duration + "\""
    } else if (msgInfo.contentType == 104) {//视频消息
      return msgInfo.senderName + '：' + '[视频]'
    }
    else if (msgInfo.contentType == 105) {//文件消息
      return msgInfo.senderName + '：' + '[文件]' + JSON.parse(msgInfo.content).fileName
    }

    else if (msgInfo.contentType == 110) {//自定义消息
      let contentInfo = JSON.parse(msgInfo.content)
      if (contentInfo.data == '1') {//车辆
        return msgInfo.senderName + '：' + '[车辆]'
      } else if (contentInfo.data == '2') {//订单
        return msgInfo.senderName + '：' + '[订单]'
      } else if (contentInfo.data == '3') {//报价订单
        return msgInfo.senderName + '：' + '[报价单]'
      } if (contentInfo.data == '6') {//纯文案
        return msgInfo.senderName + '：' + '[报价单]'
      }
      else {
        return '其他消息'
      }

    }
    else {
      return '其他消息'
    }
  }

  getUserConversationList() {
    let params = {
      pageNo: this.state.pageNo,
      pageSize: 20,
      imUserId: Constant.userInfo.imUserId,
      role: Constant.userInfo.isFranchisee == 1 ? '2' : '1',
      carId: this.props.carId,
      quotationProgressStatus: this.props.quotationProgressStatus,
      source:2
    }
    HttpUtils.postRequest(HttpUrls.getUserConversation, params).then(result => {
      this.setState({
        loading: false,
      })
      if (result.code == 0) {

        let resultList = result.data.resultList
        console.log('getUserConversationList', resultList)
        if (resultList.length > 0) {


          if (resultList.length < 20) {

            this.setState({
              isEnableLoadMore: false
            })
          } else {
            this.setState({
              isEnableLoadMore: true
            })
          }

          this.setState({
            data: this.state.data.concat(resultList),
          })

        } else {

          this.setState({
            isEnableLoadMore: false
          })
        }


      } else {
        this.setState({
          isEnableLoadMore: false
        })
      }
    }).catch(err => {
      this.setState({
        loading: false,
      })
    })
  }


  quotationReject(quotationRecordId) {
    let params = {
      quotationRecordId: quotationRecordId + ''
    }
    HttpUtils.postRequest(HttpUrls.quotationReject, params).then(result => {
      this.setState({
        loading: false,
      })
      if (result.code == 0) {
        ToastToUser('驳回成功')
        // this.setState({
        //   data: [],
        //   pageNo: 1
        // },function(){
        //   this.getUserConversationList()
        // })
      } else {
        ToastToUser(result.msg ? result.msg : result.statusText)
      }
    }).catch(err => {
      this.setState({
        loading: false,
      })
    })
  }

  cancelOrder(quotationRecordId) {
    let params = {
      quotationRecordId: quotationRecordId
    }
    HttpUtils.postRequest(HttpUrls.quotationCancel, params).then(result => {

      if (result.code == 0) {
        ToastToUser('取消成功')

      } else {
        ToastToUser(result.msg ? result.msg : result.statusText)
      }
    }).catch(err => {

    })
  }

}

const styles = StyleSheet.create({
  modalContainer: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    position:'absolute',
    top:0,
    bottom:0,
    left:0,
    right:0
  },
  overlay: {
    flex: 1,
    // backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  contentContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: '#fff',
    height: SCREEN_HEIGHT * 0.66,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 15,

  },
  title: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
  },
  closeButton: {
    fontSize: 16,
    color: '#333333',
  },
  quotationItem: {
    paddingLeft: 15,
    paddingRight: 12,
    paddingRight: 15,
    paddingBottom: 12,
    paddingTop: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  itemHeader: {
    flexDirection: 'row',

    alignItems: 'center',

  },
  userInfo: {
    flexDirection: 'column',
    flex: 1,
  },
  avatar: {
    width: 48,
    height: 48,
    borderRadius: 48,
    backgroundColor: '#eee',
    marginRight: 10,
  },
  nameContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  userName: {
    fontSize: 16,
    color: '#333333',
    fontWeight: 'bold'
  },
  date: {
    fontSize: 14,
    color: '#999',
  },
  priceContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  priceLabel: {
    fontSize: 16,
    color: '#ED542E',
  },
  price: {
    fontSize: 16,
    color: '#ED542E',
    fontWeight: '500',
  },
  actionButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  buttonContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  confirmButton: {

    paddingHorizontal: 15,
    paddingVertical: 6,
    borderRadius: 50,
    marginLeft: 10,
    borderColor: '#E5E5E5',
    borderWidth: 1
  },
  rejectButton: {
    backgroundColor: '#f5f5f5',
    paddingHorizontal: 15,
    paddingVertical: 8,
    borderRadius: 4,
    marginLeft: 10,
  },
  buttonText: {
    fontSize: 14,
    color: '#333333'
  },
  loading: {
    textAlign: 'center',
    padding: 10,
    color: '#999',
  },
  cancelBtn: {
    height: 48,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  line: {
    height: 10,
    backgroundColor: '#f6f6f6'
  }
});

export default QuotationListModal;